import React, { useEffect, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Image,
  message,
  Modal,
  Pagination,
  Row,
  Space,
  Tooltip,
  Typography,
  Empty,
  Dropdown,
  notification,
  Spin,
  Form,
  Select,
} from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData, ITableDataColor, ITableDataFabric, ProductSpuColorDetailVO } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, IMPORT_FILE_ENUM, STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import qsfLogo from '@/assets/images/logo.png'
import {
  DownOutlined,
  GoldOutlined,
  ImportOutlined,
  MenuOutlined,
  PlusOutlined,
  UploadOutlined,
} from '@ant-design/icons'
import {
  getProductSpuDevPageList,
  productSpuDevelopmentBatchStatus,
  productSpuDevUpdateSpuStatus,
  getProductColorPageList,
  getProductFabricPageList,
  getSimpleListBySearchName,
  productSpuDevelopmentimportExcel,
  productSpuDevelopmentUpdateExcel,
  productSpuDevelopmentUpdateStatusExcel,
  productSpuDevelopmentExportExcel,
  importUpdateStatusWithoutConfirm,
  quotationOrderBatchCreate,
  associatePlaning,
  getProductPlanningByPlanNo,
  importProductFabricForDev,
  importExcelForCreateForScene,
} from '@/api/goods'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import { ORDER_METTING_STATUS_OPTIONS } from '@/constant/goods'
import dayjs from 'dayjs'
import {
  downloadByUrl,
  exportNotification,
  getRecentThreeMonths,
  importNotification,
  importNotificationByFirstErrorMsg,
} from '@/utils/util'
import ImportFileModal from '@/components/ImportFileModal'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useGetClassIds from '@/hooks/useGetClassIds'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
import useModal from '@/hooks/useModal'
import { getSupplierList } from '@/api/supplier'
import { PURCHASEWAY_OPTIONS } from '@/constant/purchase'
const Index: React.FC = () => {
  let FabricTimeout: ITimeoutType
  let ColorTimeout: ITimeoutType
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormConfirm] = useForm()
  const [FormUpload] = useForm()
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [tempCode, setTempcode] = useState<
    | IMPORT_FILE_ENUM.GOODS_STYLE_IMPORT
    | IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_IMPORT
    | IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_IMPORT
    | IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_METTING_IMPORT
    | IMPORT_FILE_ENUM.GOODS_STYLESPEC_UPDATE_IMPORT
    | IMPORT_FILE_ENUM.BATCH_UPDATE_STYLE_FABRIC
    | IMPORT_FILE_ENUM.BATCH_CREATE_SPOTDEV_GOODS
  >(IMPORT_FILE_ENUM.GOODS_STYLE_IMPORT)
  const [isshowCard, setisshowCard] = useState<boolean>(false)
  const [selectRangeModal, setselectRangeModal] = useState<boolean>(false)
  const [spinning, setspinning] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const ProDevSeason = useGetProDevSeason()
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const [SizeGroupOptions, setSizeGroupOptions] = useState<IOptionItem[]>([])
  const [optionsOfSupplier, setoptionsOfSupplier] = useState<IOptionItem[]>([])
  const [styleExport, setstyleExport] = useState<{ key: string; label: string }[]>([])
  //面料option
  const [FabricOptions, setFabricOptions] = useState<IOptionItem[]>([])
  //颜色option
  const [ColorOptions, setColorOptions] = useState<IOptionItem[]>([])
  //SpuOptions
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const [batchmenuItems, setbatchmenuItems] = useState<{ key: string; label: string | React.ReactNode }[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItemsExport, setmenuItemsExport] = useState<{ key: string; label: string }[]>([])
  const [spuColorDetailId, setspuColorDetailId] = useState<string | number>()
  const defaultDateRange = getRecentThreeMonths()
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier()
  const { classIdOptions, settinyClassIds, tinyClassIds, handleClassIdChange } = useGetClassIds()
  const [sizeRangeInfos, setsizeRangeInfos] = useState<
    {
      enableStatus: number
      label: string
      sizeDetailCode: string
      sizeDetailId: string
      sizeDetailName: string
      sizeGroupId: string
      sizeGroupName: string
      value: string
    }[]
  >([])
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getProductSpuDevPageList, {
    form: form,
    defaultFieldsParams: {
      startTime: defaultDateRange,
      enableStatus: 1,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  const [tableData, settableData] = useState<ITableData[]>([])
  useEffect(() => {
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('onDev')) {
      items.push({
        key: STATUSNUM.OPEN + '',
        label: '启用款式',
      })
    }
    if (buttonCodeList.includes('offDev')) {
      items.push({
        key: STATUSNUM.CLOSE + '',
        label: '停用款式',
      })
    }
    setmenuItems(items)
    const batchmenuItems: { key: string; label: string | React.ReactNode }[] = []
    if (buttonCodeList.includes('batchAddDev')) {
      batchmenuItems.push({
        key: 'batchAddDev',
        label: '批量新建款式',
      })
    }
    if (buttonCodeList.includes('batchAddDev')) {
      batchmenuItems.push({
        key: 'batchAddDevSec',
        label: <Tooltip title="不用关联企划坑位就可以新建款式">批量新建款式草稿</Tooltip>,
      })
    }
    if (buttonCodeList.includes('batchAddSpotDevSec')) {
      batchmenuItems.push({
        key: 'batchAddSpotDevSec',
        label: '批量新建款式草稿(现采)',
      })
    }
    if (buttonCodeList.includes('batchEditDev')) {
      batchmenuItems.push({
        key: 'batchEditDev',
        label: '批量更新款式信息',
      })
    }
    if (buttonCodeList.includes('batchSelect')) {
      batchmenuItems.push({
        key: 'batchSelect',
        label: '批量更新订货状态',
      })
    }
    if (buttonCodeList.includes('batchMeetingSelect')) {
      batchmenuItems.push({
        key: 'batchMeetingSelect',
        label: '批量更新订货会状态',
      })
    }
    if (buttonCodeList.includes('batchUpdateStyleFabric')) {
      batchmenuItems.push({
        key: 'batchUpdateStyleFabric',
        label: '批量更新款式关联面料',
      })
    }
    setbatchmenuItems(batchmenuItems)
    const itemsExport: { key: string; label: string }[] = []
    if (buttonCodeList.includes('exportDev')) {
      itemsExport.push({
        key: '1',
        label: '无款式图导出（快速）',
      })
    }
    if (buttonCodeList.includes('exportDev')) {
      itemsExport.push({
        key: '2',
        label: '带款式图导出',
      })
    }
    setmenuItemsExport(itemsExport)
    const styleExport: { key: string; label: string }[] = []
    if (buttonCodeList.includes('exportSpu')) {
      styleExport.push({
        key: '3',
        label: '无款式图导出（快速）',
      })
    }
    if (buttonCodeList.includes('exportSpu')) {
      styleExport.push({
        key: '4',
        label: '带款式图导出',
      })
    }
    setstyleExport(styleExport)
    handleCacheData()
  }, [])
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        startTime: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        enableStatus: 1,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      if (cacheData.tinyClassId && cacheData.tinyClassId.length > 0) {
        settinyClassIds(cacheData.tinyClassIds)
      }
      form.setFieldsValue({
        ...cacheData,
        startTime:
          cacheData.startTime && cacheData.endTime ? [dayjs(cacheData.startTime), dayjs(cacheData.endTime)] : null,
        tinyClassIds: cacheData.tinyClassId,
        enableStatus: cacheData.enableStatus != null ? cacheData.enableStatus : null,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setFabricOptions(cacheData?.FabricOptions || [])
      setColorOptions(cacheData?.ColorOptions || [])
      delete cacheData.tinyClassId
      delete cacheData.SpuOptions
      delete cacheData.SupplierOption
      delete cacheData.FabricOptions
      delete cacheData.ColorOptions
      search({
        ...cacheData,
        startTime: cacheData.startTime ? cacheData.startTime : null,
        endTime: cacheData.endTime ? cacheData.endTime : null,
        enableStatus: cacheData.enableStatus != null ? cacheData.enableStatus : null,
      })
    }
  }
  const onCancel = () => {
    setselectRangeModal(false)
    setspuColorDetailId('')
  }
  const selectRows = (keys: React.Key[], infos: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(infos)
  }
  const changeStatus = async (info: ProductSpuColorDetailVO, status: number) => {
    const res = await productSpuDevUpdateSpuStatus({
      spuColorDetailId: info.spuColorDetailId,
      status,
    })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
    }
  }
  const reLoadPage = () => {
    search(params)
  }
  const changeStatusConfirm = async (info: ITableData, item: ProductSpuColorDetailVO) => {
    FormConfirm.setFieldsValue({
      sizeRange: info.sizeRange ? info.sizeRange.split(',') : [],
    })
    setsizeRangeInfos(info.sizeDetailVOList)
    const options =
      info?.sizeDetailVOList?.map((item) => {
        return {
          ...item,
          label: item.sizeDetailName,
          value: item.sizeDetailId,
        }
      }) || []
    setSizeGroupOptions(options)
    setspuColorDetailId(item.spuColorDetailId)
    setselectRangeModal(true)
  }
  const onSelectConfirm = async () => {
    const res = await productSpuDevUpdateSpuStatus({
      spuColorDetailId,
      status: 3,
      sizeList: sizeRangeInfos,
    })
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
    }
  }
  const handleSearchColor = (newValue = '') => {
    if (ColorTimeout) {
      clearTimeout(ColorTimeout)
      ColorTimeout = null
    }
    const getOptions = async () => {
      const res = await getProductColorPageList<ITableDataColor>({ colorGroupSearchName: newValue, enableStatus: 1 })
      if (res.code === 200) {
        const data =
          res?.data?.list?.map((item) => {
            return {
              label: item.colorDetailName,
              code: item.colorCode,
              value: item.colorDetailId + '',
              rgbValue: item.rgbValue,
              picUrl: item?.picUrl,
            }
          }) || []
        setColorOptions(data)
      }
    }
    ColorTimeout = setTimeout(getOptions, 500)
  }
  const handleSearchFabric = (newValue = '') => {
    if (FabricTimeout) {
      clearTimeout(FabricTimeout)
      FabricTimeout = null
    }
    const getOptions = async () => {
      const res = await getProductFabricPageList<ITableDataFabric>({
        searchName: newValue,
        status: 1,
      })
      if (res.code === 200) {
        const data =
          res?.data?.list?.map((item) => {
            return {
              label: item.fabricName,
              code: item.fabricCode,
              value: item.fabricId,
            }
          }) || []
        setFabricOptions(data)
      }
    }
    FabricTimeout = setTimeout(getOptions, 500)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSimpleListBySearchName<{
        spuDevId: number
        spuCode: string
        spuName: string
        designCode: string
      }>({ searchName: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: item.spuName,
              code: item.spuCode,
              value: item.spuDevId,
              designCode: item.designCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const handleClickMore = async (info: any) => {
    if (isshowCard) {
      message.warning('请切换至列表页展示再进行操作！')
      return
    }
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    if (info.key == STATUSNUM.OPEN || info.key == STATUSNUM.CLOSE) {
      const res = await productSpuDevelopmentBatchStatus({
        spuDevIds: selectedRowKeys,
        enableStatus: info.key == STATUSNUM.OPEN ? 1 : 0,
      })
      if (res.code === 200) {
        message.success('操作成功')
        setselectedRowKeys([])
        setselectedRowInfos([])
        search(params)
      }
      if (res?.code === 820000 && res?.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
          return <div key={item}>{item}</div>
        })
        notification.open({
          type: 'warning',
          message: res.msg,
          description: failInfo,
        })
      }
    }
  }
  const handleBatchMore = async (info: any) => {
    if (info.key === 'batchAddDev') {
      setTempcode(IMPORT_FILE_ENUM.GOODS_STYLE_IMPORT)
    } else if (info.key === 'batchAddDevSec') {
      setTempcode(IMPORT_FILE_ENUM.GOODS_STYLESPEC_UPDATE_IMPORT)
    } else if (info.key === 'batchEditDev') {
      setTempcode(IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_IMPORT)
    } else if (info.key === 'batchSelect') {
      setTempcode(IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_IMPORT)
    } else if (info.key === 'batchMeetingSelect') {
      setTempcode(IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_METTING_IMPORT)
    } else if (info.key === 'batchUpdateStyleFabric') {
      setTempcode(IMPORT_FILE_ENUM.BATCH_UPDATE_STYLE_FABRIC)
    } else if (info.key === 'batchAddSpotDevSec') {
      setTempcode(IMPORT_FILE_ENUM.BATCH_CREATE_SPOTDEV_GOODS)
    }
    setisUploadFileShow(true)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    if (
      tempCode === IMPORT_FILE_ENUM.GOODS_STYLE_IMPORT ||
      tempCode === IMPORT_FILE_ENUM.GOODS_STYLESPEC_UPDATE_IMPORT
    ) {
      const res = await productSpuDevelopmentimportExcel<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      const failInfo = res?.failInfo ? JSON.parse(res?.failInfo) : {}
      importNotificationByFirstErrorMsg(failInfo?.linkUrl, res?.msg)
      search(params)
      onUploadFileCancel()
      return
    }
    if (tempCode === IMPORT_FILE_ENUM.BATCH_CREATE_SPOTDEV_GOODS) {
      const res = await importExcelForCreateForScene<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      const failInfo = res?.failInfo ? JSON.parse(res?.failInfo) : {}
      importNotificationByFirstErrorMsg(failInfo?.linkUrl, res?.msg)
      search(params)
      onUploadFileCancel()
      return
    }
    if (tempCode === IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_IMPORT) {
      const res = await productSpuDevelopmentUpdateExcel<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      const failInfo = res?.failInfo ? JSON.parse(res?.failInfo) : {}
      importNotificationByFirstErrorMsg(failInfo?.linkUrl, res?.msg)
      search(params)
      onUploadFileCancel()
      return
    }
    if (tempCode === IMPORT_FILE_ENUM.BATCH_UPDATE_STYLE_FABRIC) {
      const res = await importProductFabricForDev<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      const failInfo = res?.failInfo ? JSON.parse(res?.failInfo) : {}
      importNotificationByFirstErrorMsg(failInfo?.linkUrl, res?.msg)
      search(params)
      onUploadFileCancel()
      return
    }
    let res: any
    if (tempCode === IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_IMPORT) {
      res = await productSpuDevelopmentUpdateStatusExcel<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
    }
    if (tempCode === IMPORT_FILE_ENUM.GOODS_STYLE_UPDATE_STATUS_METTING_IMPORT) {
      res = await importUpdateStatusWithoutConfirm<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
    }
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const handleClickMoreExport = async (info: any) => {
    const paramsData: Record<string, any> = {}
    if (selectedRowKeys.length > 0) {
      paramsData.spuDevIds = selectedRowKeys
    } else {
      Object.assign(paramsData, params)
    }
    setspinning(true)
    setexportLoading(true)
    const res = await productSpuDevelopmentExportExcel({
      ...paramsData,
      withPic: info.key == '1' || info.key == '3' ? 0 : 1,
      withSku: info.key == '1' || info.key == '2' ? 1 : 0,
    })
      .catch(() => setspinning(false))
      .finally(() => {
        setexportLoading(false)
        setselectedRowKeys([])
        setselectedRowInfos([])
      })
    if (res?.code === 200 && res?.data) {
      await exportNotification(res?.data, navigate).finally(() => setspinning(false))
    }
  }
  const quotationModal = useModal()
  const sendQuotationReq = async (validate: boolean) => {
    setexportLoading(true)
    let devSupplierCodeDTOS: any
    if (validate) {
      const { supplierId } = await quotationModal.form.validateFields()
      devSupplierCodeDTOS = [
        { supplierId, spuDevId: selectedRowInfos[0].spuDevId, designCode: selectedRowInfos[0].designCode },
      ]
    } else {
      devSupplierCodeDTOS = selectedRowInfos.map((item) => {
        return {
          supplierId: item.mainSupplierId,
          spuDevId: item.spuDevId,
          designCode: item.designCode,
        }
      })
    }
    const res = await quotationOrderBatchCreate({ devSupplierCodeDTOS }).finally(() => {
      setselectedRowKeys([])
      setselectedRowInfos([])
      search(params)
      quotationModal.form.resetFields()
      quotationModal.closeModal()
      setexportLoading(false)
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
    if (res?.code === 820000 && res?.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }

  const getSupList = async (newValue: string) => {
    const res = await getSupplierList<{ supplierName: string; supplierId: string }>({
      supplierClassificationCode: '成品供应商',
      keyword: newValue,
      useStatus: 1,
      cooperateStatus: 1,
      // 0 不鉴权
      authSupplier: 0,
    })
    if (res.code === 200) {
      const SupplierCYOption =
        res?.data?.list?.map((item) => {
          return {
            label: item.supplierName,
            value: item.supplierId,
          }
        }) || []
      setoptionsOfSupplier(SupplierCYOption)
    }
  }
  const onSavePlan = async (info: ITableData) => {
    const planNo = info.newplanNo
    //获取planNo的吊牌价和当前款式预估吊牌价对比
    const result = await getProductPlanningByPlanNo({ planNo: planNo || '' })
    if (result?.data && Object.keys(result.data).length > 0) {
      if (result.data?.originSalePrice && info?.originSalePrice) {
        const instance = Modal.confirm({
          title: '提示',
          content: (
            <div>
              当前吊牌价：<span style={{ color: 'red' }}>{info?.originSalePrice}</span>，企划坑位吊牌价：
              <span style={{ color: 'red' }}>{result.data?.originSalePrice}</span>，确认修改坑位吗？
            </div>
          ),
          width: 600,
          okText: '确认',
          cancelText: '取消',
          icon: null,
          onOk: async () => {
            const res = await associatePlaning({ planNo, spuDevId: info?.spuDevId }).finally(() => instance.destroy())
            if (res.code === 200) {
              message.success('操作成功')
              reLoadPage()
            }
          },
        })
      } else {
        message.warning('未填写预估吊牌价！')
      }
    }
  }
  return (
    <PageContainer className="goods_style_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['planNo'], form)}
        searchConfig={[
          {
            label: 'SPU商品',
            name: 'spuDevId',
            type: 'Select',
            placeholder: '款式编码/款式名称/设计编码/厂家款号',
            option: SpuOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          { label: '商品企划编号', name: 'planNo', type: 'Input' },
          { label: '开发季', name: 'seasonId', type: 'Select', option: ProDevSeason },
          { label: '创建时间', name: 'startTime', type: 'RangePicker', config: { showTime: true } },
          {
            label: '采购方式',
            name: 'queryPurchaseTypeList',
            type: 'Select',
            option: PURCHASEWAY_OPTIONS,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: true,
              mode: 'multiple',
              maxTagCount: 'responsive',
            },
          },
          { label: '适销季节', name: 'seasonCode', type: 'Select', option: DICTDATA.sales_season },
          {
            name: 'mainSupplierCodes',
            label: '供应商',
            type: 'Select',
            option: SupplierOption,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              mode: 'multiple',
              maxTagCount: 'responsive',
              filterOption: false,
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            name: 'tinyClassIds',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          {
            name: 'materialsKeyword',
            label: '面料',
            type: 'Input',
            placeholder: '面料名称/面料编码',
          },
          {
            name: 'colorDetailId',
            label: '款式色',
            type: 'Select',
            option: ColorOptions,
            placeholder: '请选择款式色',
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchColor,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          { label: '订货状态', name: 'spuStatus', type: 'Select', option: ORDER_METTING_STATUS_OPTIONS },
          { label: '设计师/买手', name: 'designerName', type: 'Input' },
          { label: '状态', name: 'enableStatus', type: 'Select', option: STATUSBANDOPTIONS },
          {
            label: '是否发起报价单',
            name: 'startQuotationOrder',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...vals,
            tinyClassIds: tinyClassIds.length > 0 ? tinyClassIds : null,
            queryPurchaseTypeList: vals?.queryPurchaseTypeList?.length > 0 ? vals.queryPurchaseTypeList : null,
            startTime: vals?.startTime?.[0] && dayjs(vals.startTime[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: vals?.startTime?.[1] && dayjs(vals.startTime[1]).format('YYYY-MM-DD HH:mm:ss'),
            mainSupplierCodes:
              vals.mainSupplierCodes && vals.mainSupplierCodes.length > 0 ? vals.mainSupplierCodes : null,
          }
          search({
            ...paramsData,
          })
          setCachePage({
            ...paramsData,
            tinyClassId: vals.tinyClassIds,
            SpuOptions,
            SupplierOption,
            FabricOptions,
            ColorOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          settinyClassIds([])
          const paramsData = {
            current: 1,
            size: 10,
            startTime: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
            enableStatus: 1,
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Space wrap>
              <PermissionButton
                permission="addDev"
                type="primary"
                onClick={() => {
                  navigate('/goods/style/add')
                }}
                icon={<PlusOutlined />}
              >
                新建款式
              </PermissionButton>
              <Tooltip title="不用关联企划坑位就可以新建款式">
                <PermissionButton
                  type="primary"
                  permission="addDev"
                  onClick={() => {
                    navigate('/goods/style/add?noplan=1')
                  }}
                  icon={<PlusOutlined />}
                >
                  新建款式草稿
                </PermissionButton>
              </Tooltip>
              <PermissionButton
                type="primary"
                permission="addSpotDev"
                onClick={() => {
                  navigate('/goods/style/add?noplan=1&purchaseType=1')
                }}
                icon={<PlusOutlined />}
              >
                新建款式草稿(现采)
              </PermissionButton>
              <Tooltip title="批量发起时默认按主供应商发起报价，如需发起其他工厂的报价单，请单个操作！">
                <PermissionButton
                  type="primary"
                  loading={exportLoading}
                  permission="startDevQuotation"
                  onClick={() => {
                    if (isshowCard) {
                      message.warning('请切换至列表页展示再进行操作！')
                      return
                    }
                    if (selectedRowKeys.length === 0) {
                      message.warning('请勾选需要操作的列表数据！')
                      return
                    }
                    if (selectedRowKeys.length === 1) {
                      quotationModal.openModal()
                      const { supplierName, mainSupplierId } = selectedRowInfos[0]
                      setoptionsOfSupplier([{ label: supplierName, value: mainSupplierId }])
                      quotationModal.form.setFieldValue('supplierId', mainSupplierId)
                    }
                    if (selectedRowKeys.length > 1) {
                      sendQuotationReq(false)
                    }
                  }}
                >
                  发起报价单
                </PermissionButton>
              </Tooltip>
              <PermissionButton
                permission="printDevLabel"
                onClick={() => {
                  if (isshowCard) {
                    message.warning('请切换至列表页展示再进行操作！')
                    return
                  }
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  navigate('/print?type=1', {
                    state: {
                      params: selectedRowKeys,
                    },
                  })
                }}
              >
                打印订货标签
              </PermissionButton>
              {batchmenuItems?.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: batchmenuItems,
                    onClick: handleBatchMore,
                  }}
                >
                  <Button>
                    批量操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
              {menuItems?.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </Space>
            <Space style={{ width: 100, display: 'flex', justifyContent: 'flex-end', paddingRight: 6 }}>
              {menuItemsExport.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItemsExport,
                    onClick: handleClickMoreExport,
                  }}
                >
                  <Button>
                    导出款式色明细
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
              {styleExport.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: styleExport,
                    onClick: handleClickMoreExport,
                  }}
                >
                  <Button>
                    导出款式
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
              <Tooltip placement="top" title="列表页展示">
                <div
                  className="icon_box_wrap"
                  onClick={() => {
                    setisshowCard(false)
                  }}
                >
                  <MenuOutlined style={{ fontSize: 16, color: !isshowCard ? 'var(--primary-color)' : '' }} />
                </div>
              </Tooltip>
              <Tooltip placement="top" title="图片格展示">
                <div
                  className="icon_box_wrap"
                  onClick={() => {
                    setisshowCard(true)
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  }}
                >
                  <GoldOutlined style={{ fontSize: 16, color: isshowCard ? 'var(--primary-color)' : '' }} />
                </div>
              </Tooltip>
            </Space>
          </Space>
        }
      ></SearchForm>
      {!isshowCard ? (
        <CustomTable
          className="style_special_table_wrap"
          bordered
          isSelection
          selectRows={selectRows}
          selectedRowKeys={selectedRowKeys}
          columns={useIndexColumns({
            navigate,
            changeStatus,
            changeStatusConfirm,
            reLoadPage,
            editDevPicture: buttonCodeList.includes('editDevPicture'),
            tableData,
            settableData,
            onSavePlan,
            isRoot,
          })}
          {...tableProps}
          rowKey={(rows) => rows.spuDevId}
          isScrollY
          extraHeight={26}
        />
      ) : tableProps?.dataSource?.length > 0 ? (
        <div className="card_box_wrap">
          <Row gutter={[16, 16]}>
            {tableProps?.dataSource?.map((item) => {
              return (
                <Col {...{ xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 6 }} key={item.spuDevId}>
                  <Card bordered hoverable className="cbw_card_wrap">
                    <div className="cbw_main">
                      <div className="cbwm_image_box">
                        <Image
                          rootClassName="table_image"
                          height={'100%'}
                          src={item.mainPicFileId}
                          fallback={qsfLogo}
                        />
                      </div>
                      <div
                        className="cbwm_text_box"
                        onClick={() => navigate('/goods/style/detail?spuDevId=' + item.spuDevId)}
                      >
                        <Typography.Paragraph
                          style={{ fontSize: 16, color: 'var(--primary-color)', fontWeight: 500 }}
                          ellipsis={{ rows: 2, tooltip: item.spuName }}
                        >
                          {item.spuName || '-'}
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>款式编码：</Typography.Text>
                          <Typography.Text>{item.spuCode || '-'}</Typography.Text>
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>设计编码：</Typography.Text>
                          <Typography.Text>{item.designCode || '-'}</Typography.Text>
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>商品企划编号：</Typography.Text>
                          <Typography.Link>{item.planNo || '-'}</Typography.Link>
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>款式分类：</Typography.Text>
                          <Typography.Text>{item.configClassName || '-'}</Typography.Text>
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>主供应商：</Typography.Text>
                          <Typography.Text>{item.supplierName || '-'}</Typography.Text>
                        </Typography.Paragraph>
                        <Typography.Paragraph>
                          <Typography.Text>商品系列：</Typography.Text>
                          <Typography.Text>{item.productSeries || '-'}</Typography.Text>
                        </Typography.Paragraph>
                        <Typography.Paragraph className="color_box_wrap">
                          <Typography.Text style={{ flexShrink: 0 }}>款色：</Typography.Text>
                          <div className="color_box_wrap_main">
                            {item.spuColorDetails?.map((it) => {
                              return (
                                <Tooltip placement="top" title={it.colorDetailName} key={it.colorDetailId}>
                                  {it.picUrl ? (
                                    <img style={{ display: 'inline-block', width: 30, height: 30 }} src={it?.picUrl} />
                                  ) : it.rgbValue ? (
                                    <span
                                      style={{
                                        width: 30,
                                        height: 30,
                                        backgroundColor: `rgb${it.rgbValue}`,
                                        display: 'inline-block',
                                        verticalAlign: 'middle',
                                      }}
                                    ></span>
                                  ) : (
                                    '-'
                                  )}
                                </Tooltip>
                              )
                            })}
                          </div>
                        </Typography.Paragraph>
                      </div>
                    </div>
                  </Card>
                </Col>
              )
            })}
          </Row>
          <div className="card_box_pagination">
            <Pagination {...tableProps.pagination} align="center"></Pagination>
          </div>
        </div>
      ) : (
        <div className="card_box_wrap_empty">
          <Empty
            style={{
              height: '100%',
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
            }}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </div>
      )}
      <Modal
        title="确认选中"
        open={selectRangeModal}
        maskClosable
        onCancel={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => FormConfirm.validateFields().then(() => onSelectConfirm())}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'sizeRange',
              label: '尺码范围',
              type: 'Select',
              option: SizeGroupOptions,
              placeholder: '请选择尺码范围',
              rules: [
                {
                  required: true,
                  message: '请选择尺码范围',
                },
              ],
              config: {
                optionFilterProp: 'label',
                mode: 'multiple',
                maxTagCount: 'responsive',
                onChange: (_: any, values: any) => {
                  setsizeRangeInfos(values)
                },
              },
            },
          ]}
          form={FormConfirm}
        />
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={tempCode}
      ></ImportFileModal>
      <Modal
        title="报价供应商"
        open={quotationModal.open}
        onCancel={quotationModal.closeModal}
        footer={
          <Space>
            <Button onClick={quotationModal.closeModal}>取消</Button>
            <Button
              type="primary"
              onClick={() => quotationModal.handleSubmit(() => sendQuotationReq(true))}
              loading={quotationModal.confirmLoading}
            >
              确定
            </Button>
          </Space>
        }
      >
        <Form form={quotationModal.form} layout="vertical">
          <Form.Item
            label="报价供应商"
            name="supplierId"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择报价供应商',
              },
            ]}
          >
            <Select
              options={optionsOfSupplier}
              placeholder="请选择报价供应商"
              onSearch={getSupList}
              suffixIcon={null}
              showSearch={true}
              optionFilterProp="label"
              filterOption={false}
              allowClear
              notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            ></Select>
          </Form.Item>
        </Form>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
